<template>
  <view class="container">
    <!-- <view class="alert">
      <text>
        {{ query.work === 'work_visitor_invite' ? '访客邀约' : '访客预约' }}
      </text>
    </view> -->
    <uni-nav-bar
      :border="false"
      statusBar
      :title="query.work === 'work_visitor_invite' ? '访客邀约' : '访客预约'"
      color="#000"
      left-icon="left"
      @clickLeft="onBack"
    >
    </uni-nav-bar>
    <float-button
      :name="
        query.work === 'work_visitor_invite'
          ? 'visitorinvite'
          : 'visitorPrebook'
      "
    />
    <view class="myForm">
      <uni-forms
        ref="valiForm"
        :rules="rules"
        v-model="formData"
        label-position="top"
        label-width="150"
        :border="false"
        err-show-type="toast"
      >
        <uni-forms-item label="访客姓名" required name="visitorName">
          <uni-easyinput v-model="formData.visitorName" placeholder="请输入" />
        </uni-forms-item>
        <uni-forms-item label="访客单位" required name="visitorUnit">
          <uni-easyinput v-model="formData.visitorUnit" placeholder="请输入" />
        </uni-forms-item>
        <uni-forms-item
          label="访客身份证人像面"
          required
          name="idcardRenxiangOssId"
        >
          <FileUploader
            limit="1"
            mode="grid"
            v-model="formData.idcardRenxiangOssId"
          />
        </uni-forms-item>
        <uni-forms-item label="访客身份证国徽面" name="idcardGuohuiOssId">
          <FileUploader
            limit="1"
            mode="grid"
            v-model="formData.idcardGuohuiOssId"
          />
        </uni-forms-item>
        <uni-forms-item label="访客电话" required name="visitorPhone">
          <uni-easyinput v-model="formData.visitorPhone" placeholder="请输入" />
        </uni-forms-item>
        <uni-forms-item label="来访前地址" required name="address">
          <uni-easyinput v-model="formData.address" placeholder="请输入" />
        </uni-forms-item>
        <uni-forms-item
          label="访客身体状况"
          required
          name="visitorPhysicalCondition"
        >
          <uni-easyinput
            v-model="formData.visitorPhysicalCondition"
            placeholder="请输入"
          />
        </uni-forms-item>
        <uni-forms-item label="来访方式" required name="visitWay">
          <uni-data-select
            placeholder="请选择"
            :localdata="visitWay"
            v-model="formData.visitWay"
          />
        </uni-forms-item>
        <uni-forms-item label="来访事由" required name="visitReason">
          <uni-easyinput
            type="textarea"
            v-model="formData.visitReason"
            placeholder="请输入"
          />
        </uni-forms-item>
        <uni-forms-item label="来访日期" required name="date">
          <uni-datetime-picker
            type="datetimerange"
            hide-second
            :start="new Date().getTime()"
            v-model="formData.date"
          />
        </uni-forms-item>
        <uni-forms-item
          label="来访时长"
          name="hours"
          v-if="formData.date.length !== 0"
        >
          <view
            >{{ `${formData.date[0]} ~ ${formData.date[1]}` }}<br />共计
            {{ formData.hours }} 小时</view
          >
        </uni-forms-item>
        <uni-forms-item label="选择受访人" required name="entourageUserId">
          <template v-slot:label>
            <view class="myLabel">
              <view class="text"><text class="star">*</text>选择受访人员</view>
              <uni-icons
                type="plus-filled"
                size="30"
                color="#409EFF"
                @click="onLocation('/pages/user/select?multiple=0')"
              />
            </view>
          </template>
          <view
            :style="{
              color: formData.userName ? '#555' : '#888',
              marginTop: '10rpx',
            }"
            >{{ formData.userName || '点击右侧图标选择' }}</view
          >
        </uni-forms-item>
        <uni-forms-item label="备注" name="described">
          <uni-easyinput
            type="textarea"
            v-model="formData.described"
            placeholder="请输入"
          />
        </uni-forms-item>

        <!-- <uni-forms-item label="拜访时间" required name="time">
					<button class="button" size="mini" type="primary" @click="onToggle('bottom')">选择时间</button>
				</uni-forms-item> -->
      </uni-forms>
    </view>
    <view class="btnBox">
      <button class="btn" type="primary" @click="onSubmit('valiForm')">
        提交
      </button>
      <!-- #ifdef MP-WEIXIN -->
      <button
        @click="onShareImg"
        v-if="shareImg && query.work === 'work_visitor_invite'"
      >
        分享给访客
      </button>
      <!-- #endif -->
    </view>
  </view>
</template>

<script>
import {
  netCompleteTask,
  netStartWorkFlow,
  addVisitorInvite,
} from '@/api/workflow';
import config from '@/common/config';
import FileUploader from '@/components/FileUploader/index.vue';
export default {
  components: {
    FileUploader,
  },
  data() {
    return {
      query: {},
      shareImg: '',
      // 表单数据
      visitWay: [
        {
          text: '驾车',
          label: '驾车',
          value: '1',
        },
        {
          text: '出租车/网约车',
          label: '出租车/网约车',
          value: '2',
        },
        {
          text: '步行',
          label: '步行',
          value: '3',
        },
        {
          text: '骑行',
          label: '骑行',
          value: '4',
        },
      ],
      formData: {
        date: [],
      },
      // 规则
      rules: {
        visitorName: {
          rules: [
            {
              required: true,
              errorMessage: '姓名不能为空',
            },
          ],
        },
        visitorUnit: {
          rules: [
            {
              required: true,
              errorMessage: '请输入访客单位',
            },
          ],
        },
        visitReason: {
          rules: [
            {
              required: true,
              errorMessage: '请输入来访事由',
            },
          ],
        },
        address: {
          rules: [
            {
              required: true,
              errorMessage: '请输入地址',
            },
          ],
        },
        visitWay: {
          rules: [
            {
              required: true,
              errorMessage: '请选择来访方式',
            },
          ],
        },
        visitorPhysicalCondition: {
          rules: [
            {
              required: true,
              errorMessage: '请输入访客身体状况',
            },
          ],
        },
        date: {
          rules: [
            {
              required: true,
              errorMessage: '请选择日期',
            },
          ],
        },
        entourageUserId: {
          rules: [
            {
              required: true,
              errorMessage: '请选择受访人',
            },
          ],
        },
        idcardRenxiangOssId: {
          rules: [
            {
              required: true,
              errorMessage: '请上传身份证照片',
            },
          ],
        },
        visitorIdCard: {
          rules: [
            {
              required: true,
              errorMessage: '身份证不能为空',
            },
            {
              pattern:
                /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(10|11|12))([0-2]\d|30|31)\d{3}[0-9Xx]$/,
              errorMessage: '请输入正确的身份证号码',
            },
          ],
        },
        visitorPhone: {
          rules: [
            {
              required: true,
              errorMessage: '手机号不能为空',
            },
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              errorMessage: '请输入正确的手机号码',
            },
          ],
        },
      },
    };
  },
  watch: {
    'formData.date': {
      handler(newVal) {
        if (newVal.length !== 0) {
          this.formData.hours = (
            (Date.parse(new Date(newVal[1])) -
              Date.parse(new Date(newVal[0]))) /
            (1000 * 60 * 60)
          ).toFixed(2);
        }
      },
      immediate: false,
      deep: true,
    },
  },
  onLoad(query) {
    // if (
    //   (query.work == 'work_visitor_invite' &&
    //     !this.$util.getMenuItem('visitorInvite')) ||
    //   this.$util.getMenuItem('visitorInvite').selectStatus != 1 ||
    //   (query.work == 'work_visitor_prebook' &&
    //     !this.$util.getMenuItem('visitorPrebook')) ||
    //   this.$util.getMenuItem('visitorPrebook').selectStatus != 1
    // ) {
    //   console.log('没有此菜单权限');
    //   return this.onBack();
    // }
    this.query = query;
  },
  onShow() {
    this.$bus.on('addUserData', (res) => {
      if (res && res.length !== 0) {
        this.formData.userName = res[0].nickName;
        this.formData.entourageUserId = res[0].userId;
      }
    });
  },
  onUnload() {
    this.$bus.off('addUserData');
  },
  methods: {
    // 分享
    onShareImg() {
      uni.showLoading({ title: '获取二维码中' });
      uni.downloadFile({
        url: config.url + this.shareImg,
        success: (res) => {
          uni.hideLoading();
          uni.showShareImageMenu({
            path: res.tempFilePath,
          });
        },
        fail: (err) => {
          uni.hideLoading();
          uni.showToast({ icon: 'error', title: '获取失败' });
        },
      });
    },
    // 车牌内容
    onNumChange(e) {
      // 将中文逗号替换为英文逗号
      e = e.replace(/,/g, ',');
    },
    // 选择时间组件
    onToggle(type) {
      this.$refs.popup.open(type);
    },
    // 提交
    onSubmit(ref) {
      this.$refs[ref]
        .validate()
        .then((res) => {
          console.log('success', res);
          // loading提示
          uni.showLoading({ title: '操作中' });
          // 提交接口
          let api = addVisitorInvite;
          let params = {
            ...res,
            visitTime: res.date[0] + ':00',
            leaveTime: res.date[1] + ':00',
            applicationType: this.query.type,
            idcardRenxiangOssId: res.idcardRenxiangOssId
              .map((item) => item.ossId)
              .join(),
          };
          if (res.idcardGuohuiOssId) {
            params.idcardGuohuiOssId = params.idcardGuohuiOssId
              .map((item) => item.ossId)
              .join();
          }
          api(params).then((res) => {
            if (this.query.work === 'work_visitor_invite') {
              this.shareImg = res.data.qrcodeUrl;
            }
            this.onStartWorkFlow(res.data);
          });
        })
        .catch((err) => {
          console.log('err', err);
        });
    },
    // 开启工单流
    onStartWorkFlow(data) {
      let params = {
        tableName: this.query.work,
        businessKey: data.id || data.visitorInviteId,
        variables: { entity: data },
      };
      netStartWorkFlow(params).then((res) => {
        this.onCompleteTask(res.data, params);
      });
    },
    // 完成工单流
    onCompleteTask(d, p) {
      let params = {
        taskId: d.taskId,
        variables: {},
        wfCopyList: [],
        messageType: ['1'],
        taskVariables: p.variables,
      };
      netCompleteTask(params).then((res) => {
        uni.hideLoading();
        uni.showToast({
          title: `提交成功`,
        });
        // 重置
        this.onReset();
      });
    },
    // 重置表单
    onReset() {
      this.formData = this.$options.data().formData;
    },
    // 跳转页面
    onLocation(url) {
      uni.navigateTo({
        url,
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  min-height: calc(100vh - var(--window-bottom) - 200rpx);
  padding: 200rpx 36rpx;
  padding-bottom: calc(var(--window-bottom) + 200rpx);
  display: flex;
  flex-direction: column;
  .uni-navbar {
    width: 100%;
    position: fixed;
    top: 0;
    left: 0;
    background-color: #fff;
    z-index: 9;
  }

  .alert {
    padding: 16rpx;
    margin: 24rpx 0;
    text-align: center;
    background: #ddeafa;
    border-radius: 12rpx;
    text {
      font-size: 32rpx;
      font-weight: 600;
      color: #3a84ff;
    }
  }

  .myForm {
    padding: 24rpx;
    background: #fff;
    border-radius: 12rpx;

    ::v-deep .uni-forms-item__label {
      width: 40%;
      color: #333333;
      font-size: 28rpx;
      font-weight: bold;
      position: relative;

      &::after {
        // content: "";
        width: 100%;
        height: 1rpx;
        background: #000;
        position: absolute;
        left: 14rpx;
        bottom: 20rpx;
      }
    }

    .myLabel {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .text {
        color: #333333;
        font-size: 28rpx;
        font-weight: bold;
      }
      .star {
        color: #dd524d;
      }
    }
  }

  .btnBox {
    // position: fixed;
    // left: 36rpx;
    // right: 36rpx;
    // bottom: calc(var(--window-bottom) + 60rpx);
    .btn {
      width: 100%;
      height: 92rpx;
      font-size: 40rpx;
      color: #ffffff;
      line-height: 92rpx;
      background: #3681ff;
    }
    button {
      margin-top: 20rpx;
    }
  }
}
</style>
